<style lang="scss" scoped>
.patrol-list-container {
  .el-pagination {
    padding: 16px 0;

    .btn-prev,
    .btn-next {
      margin: 0;
      margin-right: 6px;
    }
  }

  .header-container {
    padding-bottom: 20px;

    &__item {
      margin-right: 10px;
    }
    .content{
    display: flex;
    margin-top: 20px;
    .sift{
      margin-right: 40px;
    }
    .el-input{
      width: 200px;
    }

    .name{
      margin-right: 10px
    }
  }
  }

  .actions {
    .el-button {
      margin: 5px;
    }
  }
  .block{
    display: flex;
    justify-content: center;
  }

}
</style>

<script>
import dayjs from 'dayjs'
import CreatePatrolPlanDialog from './components/createPatrolPlan.vue'
import UpdatePatrolPlanDialog from './components/editPatrolPlan.vue'
import PatrolPlanDetails from './components/patrolPlanDetails.vue'
import DeletePatrolPlan from './components/deletePatrolPlan.vue'

import { patrolPlans } from '@/api/watchman'

export default {
  components: {
    CreatePatrolPlanDialog,
    UpdatePatrolPlanDialog,
    PatrolPlanDetails,
    DeletePatrolPlan
  },
  data() {
    return {
      patrolPlans: [],
      idToBeEdited: null,
      idToBeLookUp: null,

      loadingStatuses: {
        loading: false
      },

      visibleStatuses: {
        createPatrolPlanDialog: false,
        updatePatrolPlanDialog: false,
        patrolPlanDetails: false,

        deletePopover: false
      },

      pagination: {
        size: 10,
        current: 1,
        total: 0
      },
      name: ''
    }
  },
  computed: {
    patrolPlansFormatted() {
      return this.patrolPlans.map((plan) => {
        const { id, name, number, created_at, updated_at } = plan

        return {
          id,
          name,
          number,
          createdAt: created_at,
          updatedAt: updated_at
        }
      })
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // Events
    handlePageChange(currentPage) {
      this.pagination.current = currentPage
      this.refreshTable()
    },
    handlePageSizeChange(size) {
      this.pagination.size = size
      this.refreshTable()
    },

    handleCreateSuccess() {
      this.$message.success('添加成功')
      this.refreshTable()
    },
    handleUpdateSuccess() {
      this.$message.success('保存成功')
      this.refreshTable()
    },
    handleDelSuccess() {
      this.$message.success('删除成功')
      this.refreshTable()
    },
    handleDelFail(e) {
      console.log(e)
      this.$message.error(e.message)
    },

    handleEdit(index, patrolPlan) {
      this.idToBeEdited = patrolPlan.id
      this.visibleStatuses.updatePatrolPlanDialog = true
    },
    handleCreate() {
      this.visibleStatuses.createPatrolPlanDialog = true
    },
    handleLookUp(index, patrolPlan) {
      this.visibleStatuses.patrolPlanDetails = true
      this.idToBeLookUp = patrolPlan.id
    },

    sleep(t) {
      return new Promise((r) => setTimeout(r, t))
    },

    async refreshTable() {
      try {
        if (this.loadingStatuses.loading) return
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    async getPatrolList() {
      const { current, size } = this.pagination

      const params = {
        page: current,
        paginate: size,
        name: this.name
      }

      const result = await patrolPlans(params)
      this.patrolPlans = result.data
      this.pagination.total = result.meta.total
    },
    async loadData() {
      const result = await Promise.allSettled([this.getPatrolList()])

      const failTasks = result.filter((task) => task.status === 'rejected')
      if (failTasks.length <= 0) return

      throw failTasks[0].reason
    },
    async initData() {
      try {
        this.loadingStatuses.loading = true
        await this.sleep(400)
        await this.loadData()
        this.loadingStatuses.loading = false
      } catch (e) {
        this.loadingStatuses.loading = false
      }
    },
    onSubmit() {
      this.page = 1
      this.getPatrolList()
    }
  }
}
</script>

<template>
  <div class="app-container patrol-list-container">
    <CreatePatrolPlanDialog
      v-model="visibleStatuses.createPatrolPlanDialog"
      @success="handleCreateSuccess"
    />

    <UpdatePatrolPlanDialog
      v-model="visibleStatuses.updatePatrolPlanDialog"
      :patrol-id="idToBeEdited"
      @success="handleUpdateSuccess"
    />

    <PatrolPlanDetails
      v-model="visibleStatuses.patrolPlanDetails"
      :patrol-id="idToBeLookUp"
    />
    <el-card shadow="never" style="margin-bottom: 20px; border: none;">
      <div class="header-container" style="padding-bottom: 0;">
        <div class="content" style="margin-top: 0">
          <div class="sift">
            <span class="name">排班名称</span>
            <el-input
              v-model="name"
              class="search"
              placeholder="请输入排班名称"
            />
          </div>
          <div>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <el-card shadow="never" style="border: none;">
      <div class="header-container">
        <el-button
          class="header-container__item"
          type="primary"
          icon="el-icon-plus"
          @click="handleCreate"
        >
          创建排班
        </el-button>

        <el-button
          class="header-container__item"
          icon="el-icon-refresh-right"
          @click="refreshTable"
        >
          刷新
        </el-button>
      </div>

      <el-row :gutter="40">
        <el-col :span="24">
          <el-table
            v-loading="loadingStatuses.loading"
            :data="patrolPlansFormatted"
            style="width: 100%"
            border
          >

            <el-table-column prop="name" label="名称" width="180" />

            <el-table-column prop="number" label="班次数量" />

            <el-table-column prop="createdAt" label="创建时间" />

            <el-table-column prop="updatedAt" label="最后修改" />

            <el-table-column prop="actions" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="actions">
                  <el-button
                    circle
                    plain
                    icon="el-icon-view"
                    @click="handleLookUp(scope.$index, scope.row)"
                  />

                  <el-button
                    circle
                    plain
                    type="primary"
                    icon="el-icon-edit"
                    @click="handleEdit(scope.$index, scope.row)"
                  />

                  <DeletePatrolPlan
                    :patrol-id="scope.row.id"
                    @success="handleDelSuccess"
                    @fail="handleDelFail"
                  />
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <el-pagination
            style="padding-bottom: 0;"
            class="block"
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="pagination.current"
            :page-sizes="[10, 50, 100]"
            :page-size="pagination.size"
            :total="pagination.total"
            :disabled="loadingStatuses.loading"
            @size-change="handlePageSizeChange"
            @current-change="handlePageChange"
          />
        </el-col>
      </el-row>
    </el-card>

  </div>
</template>
